package com.hxb.burp.utils;

import mjson.Json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


/**
 * burp_extendsion2
 *
 * @author 黄小斌
 * @date 2023-10-27
 */
public class HttpUtils {

    public static final String ENCODE = "UTF-8";

    public static AjaxResult sendPost(String url, String data) {
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            OutputStream os = connection.getOutputStream();
            os.write(data.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
            int statusCode = connection.getResponseCode();
            if (200 == statusCode) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder stringBuffer = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                String response = stringBuffer.toString();
                Json json = Json.object();
                json.set("statusCode", statusCode);
                json.set("response", response);
                String msg = "Response Status:" + statusCode + ",Response Data: " + response;
                connection.disconnect();
                return AjaxResult.success(json);
            }
            return AjaxResult.error(10, "response code:" + statusCode);
        } catch (IOException e) {
            return AjaxResult.error(99, "response msg:" + e.getMessage());
        }
    }
}
